#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

ESP8266WiFiMulti wifiMulti;           // 建立ESP8266WiFiMulti对象

const char* host = "bemfa.com"; // 网络服务器地址
const int httpPort = 8340;              // http端口80

// WiFi连接信息
const char*  WiFi_SSID = "ling";
const char*  WiFi_Password = "ling....9";

// 建立WiFi客户端对象，对象名称client
WiFiClient client;

void setup(){
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);    // 设置ESP8266为无线终端模式

  wifiMulti.addAP(WiFi_SSID, WiFi_Password);
  Serial.println("Connecting ...");

  // 尝试进行wifi连接。
  int i = 0;
  while (wifiMulti.run() != WL_CONNECTED) {
    delay(1000);
    Serial.print(i++); Serial.print(' ');
  }

  // WiFi连接成功后将通过串口监视器输出连接成功信息
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());              // WiFi名称
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());           // IP

  //连接巴法云
  client.connect(host, httpPort);
  Serial.print("conneted bamfa!\n");
  //订阅主题test
  client.print("cmd=1&uid=<填你们自己的uid>&topic=test\r\n");

}


void loop(){
  // 判断登录状态
  if(not client.connected()){
    //连接巴法云
    client.connect(host, httpPort);
    Serial.print("reconneted bamfa!\n");
    //订阅主题test
    client.print("cmd=1&uid=<填你们自己的uid>&topic=test\r\n");

  }
  //输出结果
  while (client.connected() || client.available()){
      if (client.available()){
        String line = client.readStringUntil('\n');
        Serial.println(line);
        if(line=="1")
        { digitalWrite(0, HIGH); }
        else{ digitalWrite(0, LOW);}
      }
    }
  delay(10);
}

